<template>
  <div class="u-page">
    <!-- 顶部按钮 -->
    <div class="u-sticky u-flex u-row-between u-box u-bcl-white">
      <div class="u-cl-content u-pointer" @click="goBack">取消</div>
      <div class="u-cl-primary u-pointer" @click="save">保存</div>
    </div>

    <div class="u-box">
      <!-- 标题 -->
      <div class="u-mb-15 u-mt-15">
        <div class="u-fz-26 u-font-bold">
          {{ info.title }}（{{ isSelectList.length }}/{{ maxlength }}）
        </div>
        <div class="u-pt-10 u-cl-content">{{ info.tips }}</div>
        <div class="u-pb-10 u-cl-content">自定义标签数不低于3个，每个标签的字数不低于3个字。</div>
      </div>

      <!-- 选项列表 -->
      <ul>
        <li
            class="u-inline u-pointer"
            v-for="(item, index) in list"
            :key="index"
            @click="selectItem(item)"
        >
          <u-tag
              :text="item.label"
              :type="item.isSelect ? 'primary' : 'info'"
              :mode="item.isSelect ? 'light' : 'dark'"
          ></u-tag>
        </li>

        <!-- 添加标签按钮 -->
        <li class="u-inline">
          <div class="u-center add-btn u-pointer" @click="visible1 = true">
            <div class="u-mr-5">
              <u-icon class="u-cl-primary" name="plus"></u-icon>
            </div>
            <div class="u-cl-primary">自定义</div>
          </div>
        </li>
      </ul>
      <div style="margin: 10px"><br></div>

      <!-- 添加固定标签 -->
      <div class="u-pt-20">
        <div class="u-title u-flex u-row-between u-col-center u-mb-10 border-bottom">
          <div class="u-flex u-col-center u-flex-1">
            <div class="job-name u-mb-5">
              热门标签
            </div>
          </div>
        </div>
        <ul v-for="(item, index) in hotList">
          <div class="tag-title">{{ item.tagName }}</div>
          <li
              class="u-inline u-pointer"
              v-for="(citem, cindex) in item.destags"
              :key="cindex"
              @click="selectHotItem(citem)"
          >
            <u-tag
                :text="citem.label"
                :type="citem.isSelect ? 'primary' : 'info'"
                :mode="citem.isSelect ? 'light' : 'dark'"
            ></u-tag>
          </li>
        </ul>
      </div>

    </div>
    <!-- 添加自定义标签 -->
    <u-modal
        ref="uModal"
        title="添加自定义标签"
        show-cancel-button
        async-close
        @confirm="addTag"
        v-model="visible1"
    >
      <div class="u-p-20">
        <u-form :model="form" ref="uForm">
          <u-form-item label="名称" label-position="top">
            <u-input v-model="form.key1" placeholder="请填写标签，符号无效"></u-input>
          </u-form-item>
        </u-form>
      </div>
    </u-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      info: {},
      modes: {
        1: {
          title: "专业技能设置",
          tips: "我们建议您从“职业定位”+“从事经验”+“技能特长”的组合来定义您的专业技能，精确的标签能提升需求匹配率哦！" +
              "自定义标签数不低于3个，每个标签的字数不低于3个字。",
        },
        2: {
          title: "兴趣爱好设置",
          tips: "我们建议您从“兴趣类型”+“培养时长”+“具体爱好”的组合来定义您的兴趣爱好，精确的爱好能匹配到更多志同道合到小伙伴哦！" +
              "自定义标签数不低于3个，每个标签的字数不低于3个字。",
        },
        3: {
          title: "标签匹配",
          tips: "自定义本需求的最佳拍档标签，系统将根据您的标签，精准匹配拍档，助您早日解决烦恼哦～",
        },
        4: {
          title: "需求标签",
          tips: "自定义需求关键字，系统将根据您的标签，精准匹配拍档！",
        }
      },
      list: [],
      maxlength: 1000,

      form: {
        key1: "",
      },

      visible1: false,
      show1: false,
      show2: false,
      show3: true,

      labelType: "",
      hotList: []
    };
  },

  async onLoad() {
    this.info = this.modes[this.$query.mode || 1];


    if (this.$query.mode == 1) {
      this.show1 = true
      this.labelType = "skill";
    }
    if (this.$query.mode == 2) {
      this.show2 = true
      this.labelType = "hobby";
    }
    if (this.$query.mode == 3) {
      this.show3 = false
      this.labelType = "match";
    }
    if (this.$query.mode == 4) {
      this.show4 = true
      this.labelType = "keyword";
    }
    await this.getTagList();
    await this.initHotTagList();
    // 已选中的标签回显，我这边的list是定义死的，如果从接口获取的话，记得把这段代码放到请求完毕，list赋值之后
    let prevPageIsSelectList = uni.getStorageSync("create") || [];
    this.list = prevPageIsSelectList
    if (this.list.length > 0) {
      this.list.forEach((item) => {
        prevPageIsSelectList.forEach((citem) => {
          if (item.value == citem.value) {
            item.isSelect = true;
          }
          //标签同步选中或者取消
          this.isExistInHotArr(this.hotList, item, true)
        });
      });
    }
    // 清空
    // uni.setStorageSync("prevPageIsSelectList", []);
  },

  methods: {
    /**
     * 保存
     */
    save() {
      if (this.isSelectList.length < 3) {
        return this.$u.toast("至少选择3个标签哦~");
      }
      // 保存选中的标签列表
      if(this.$query.type){
        uni.$emit(this.$query.type, this.isSelectList);
      }else{
        uni.$emit("saveTagList", this.isSelectList);
      }
      this.goBack();
    },

    /**
     * 添加自定义标签
     */
    async addTag() {
      if (this.form.key1 && this.form.key1.length > 2 && !this.hasSpecial(this.form.key1)) {
        // 添加成功
        setTimeout(() => {
          this.list.push({
            label: this.form.key1,
            value: this.form.key1,
            isSelect: true,
          });
          this.form.key1 = "";
          this.visible1 = false;
          this.$refs.uModal.clearLoading();

          this.saveTagToDb();
        }, 1000);
      } else {
        if (this.hasSpecial(this.form.key1)) {
          this.$u.toast("标签不能包含符号");
        } else {
          this.$u.toast("字数不低于三个字");
        }
        this.$refs.uModal.clearLoading();
      }
    },

    /**
     * 保存标签到数据库
     */
    async saveTagToDb() {
      const userInfo = uni.getStorageSync('userInfo');
      let saveList = [];
      this.list.forEach((items, index) => {
        saveList.push({
          label: items.label,
          value: items.value,
          isSelect: false,
        })
      })
      await this.$u.api.initTagList({
        userId: userInfo.userId,
        tagList: saveList,
        mode: "save",
        tag: this.labelType,
        loading: false
      });
    },

    /**
     * 初始化标签
     */
    async getTagList() {
      const userInfo = uni.getStorageSync('userInfo');
      let data = await this.$u.api.initTagList({
        userId: userInfo.userId,
        mode: "get",
        tag: this.labelType,
        loading: false
      });
      let jsonStr = JSON.parse(JSON.stringify(data))
      if (jsonStr.status == "1") {
        let tagListTemp = jsonStr.tagList
        if (tagListTemp != null && tagListTemp != '') {
          this.list = this.RestructuringLabel(tagListTemp);
        }
      }
    },

    /**
     * 初始化热门标签
     */
    async initHotTagList() {
      const userInfo = uni.getStorageSync('userInfo')
      let result = await this.$u.api.unifyRequest({
        appid: 'OpenTB',
        wf_num: 'R_OpenTB_B003',
        userId: userInfo.userId,
        loading: true // 默认发起请求会有一个全局的Loading，设置false可去掉
      });
      if (result.code == '200') {
        this.hotList = result.data
      }
    },

    /**
     * 选中标签
     */
    selectItem(item) {
      let isSelect = !item.isSelect;

      if (isSelect && this.isSelectList.length >= this.maxlength) {
        return this.$u.toast("最多选择3个标签哦~");
      } else {
        item.isSelect = isSelect;
        //标签同步选中或者取消
        this.isExistInHotArr(this.hotList, item, isSelect)
      }
    },

    /**
     * 选中热门标签
     */
    selectHotItem(item) {
      let isSelect = !item.isSelect;
      item.isSelect = isSelect;
      if (this.isExistInArr(this.list, item, 'N')) {
        this.isExistInArr(this.list, item, isSelect)
      } else {
        this.list.push(item)
      }
    },

    /**
     * 将数组中的某个元素更改为选中/取消状态
     */
    isExistInArr(arr, item, isSelect) {
      let flag = false
      arr.forEach((titem) => {
        if (item.label == titem.label) {
          if (isSelect != 'N') {
            titem.isSelect = isSelect
          }
          flag = true
        }
      })
      return flag
    },

    /**
     * 将数组中的某个元素更改为选中/取消状态(点击个人标签列表)
     */
    isExistInHotArr(arr, item, isSelect) {
      let flag = false
      arr.forEach((titem) => {
        let childArr = titem.destags
        childArr.forEach((citem) => {
          if (item.label == citem.label) {
            if (isSelect != 'N') {
              citem.isSelect = isSelect
            }
            flag = true
          }
        })
      })
      return flag
    }

  },

  computed: {
    isSelectList() {
      return this.list.filter((item) => item.isSelect) || [];
    },
  },
};
</script>

<style lang="scss" scoped>
.u-page {
  /deep/ .u-tag {
    &.u-mode-dark-info {
      border: 2 rpx solid transparent;
    }
  }

  .add-btn {
    width: 150 rpx;
    height: 52 rpx;
    font-size: 22 rpx;
    margin: 0 10 rpx 10 rpx 0;
    border: 2 rpx dashed $u-type-primary;
  }

  ._span {
    color: #3b79fe;
    margin: 5px;
  }

  .border-bottom {
    border-bottom: 1 rpx #e5e5e5 solid;
  }

  .tag-title {
    color: #a29e9e;
    padding-bottom: 10 rpx;
  }
}
</style>
